package thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class DiedReentrantLocklockInterruptibly extends Thread {
    static ReentrantLock reentrantLock1 = new ReentrantLock();

    static ReentrantLock reentrantLock2 = new ReentrantLock();

    int i = 1;

    public static void main(String[] args) {
        DiedReentrantLocklockInterruptibly zhangsan = new DiedReentrantLocklockInterruptibly(1, "zhangsan");
        DiedReentrantLocklockInterruptibly lisi = new DiedReentrantLocklockInterruptibly(2, "lisi");
        zhangsan.start();
        lisi.start();
        zhangsan.interrupt();
        lisi.interrupt();

    }

    public DiedReentrantLocklockInterruptibly(int i, String name) {
        super(name);
        this.i = i;
    }

    @Override
    public void run() {
       if (i==1){
           try {
               reentrantLock1.lockInterruptibly();
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
           try {
               TimeUnit.SECONDS.sleep(1);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
           try {
               reentrantLock2.lockInterruptibly();
           } catch (InterruptedException e) {
               e.printStackTrace();
           }

       }else if (i==2){
           try {
               reentrantLock2.lockInterruptibly();
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
           try {
               TimeUnit.SECONDS.sleep(1);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
           try {
               reentrantLock1.lockInterruptibly();
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }
       if (reentrantLock1.isHeldByCurrentThread()){
           reentrantLock1.unlock();
       }
       if (reentrantLock2.isHeldByCurrentThread()){
           reentrantLock2.unlock();
       }
    }
}
